package cn.edu.zsc.rbac.service.array;

import cn.edu.zsc.rbac.domain.dto.BaseDto;
import cn.edu.zsc.rbac.domain.dto.UserDto;
import cn.edu.zsc.rbac.domain.entity.BaseEntity;
import cn.edu.zsc.rbac.domain.entity.Dept;
import cn.edu.zsc.rbac.domain.entity.User;
import cn.edu.zsc.rbac.domain.vo.BaseVo;
import cn.edu.zsc.rbac.domain.vo.DeptVo;
import cn.edu.zsc.rbac.domain.vo.Result;
import cn.edu.zsc.rbac.service.IBaseService;

import java.util.Arrays;

/**
 * 业务层-基类
 *
 * @author 陈奕君
 * @since 2025/5/19 12:55
 */
abstract class BaseService
        <Entity extends BaseEntity, Dto extends BaseDto,Vo extends BaseVo>
        implements IBaseService<Entity, Dto> {

     static final int DATA_SIZE = 100;

     Entity[] data;

     Vo[] temp;

    private int idCounter = 1;

    @Override
    public boolean existsById(int id) {
        return id>=1 && id < idCounter && data[id] != null;
    }

    @Override
    public Entity findById(int id) {
        if (existsById(id)) {
            return data[id];
        }
        return null;
    }

    abstract Vo convertToVo(Entity entity);

    @Override
    public Result list() {
        int length = 0;
        for(int i = 1;i<idCounter;i++)
        {
            if(data[i] != null)
            {
                temp[length++] = convertToVo(data[i]);
            }
        }
        return Result.success("查询部门列表成功！", Arrays.copyOf(temp, length));
    }

    abstract Entity createEntity(Dto dto, int id);

    @Override
    public Result create(Dto dto) {
        if (idCounter > DATA_SIZE) {
            return Result.failure("创建部门失败，超出了存储容量！");
        }
        Entity entity = createEntity(dto, idCounter++);
        data[entity.getId()] = entity;
        return Result.success("创建部门成功！", null);
    }

    abstract void updateEntity(Dto dto, Entity entity);

    @Override
    public Result update(Dto dto, int id) {
        if (!existsById(id)) {
            return Result.failure("更新部门失败，部门不存在！");
        }
        Entity entity = data[id];
        updateEntity(dto, entity);
        return Result.success("更新部门成功！", null);
    }
}
